package l2hc.gameserver.model.votes;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Calendar;
import java.util.StringTokenizer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import l2hc.commons.dbutils.DbUtils;
import l2hc.gameserver.Config;
import l2hc.gameserver.ThreadPoolManager;
import l2hc.gameserver.data.xml.holder.ItemHolder;
import l2hc.gameserver.database.DatabaseFactory;
import l2hc.gameserver.model.Player;
import l2hc.gameserver.model.World;

/**
 * @user: Shaitan 
 * @modified: KilRoy
 * @date: 19.01.12 22:39
 */
public class L2Top
{
	BufferedReader reader;
	private static L2Top Instance = new L2Top();
	private static final Logger _log = LoggerFactory.getLogger(L2Top.class);
	public static L2Top getInstance()
	{
		return Instance;
	}

	private L2Top()
	{
		if(Config.L2_TOP_ENABLE)
		{
			ThreadPoolManager.getInstance().scheduleAtFixedRate(new startParce(), 60000, Config.L2_TOP_REFRESH_TIME * 60 * 1000);
		}
	}

	private class startParce implements Runnable
	{
		public void run()
		{
			try
			{
				getPage(Config.L2_TOP_URL);
				parse();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}

	private void getPage(String address)
	{
		try
		{
			URL url = new URL(address);
			reader = new BufferedReader(new InputStreamReader(url.openStream(), "windows-1251"));
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unused")
	private void parse()
	{
		String line;
		int i = 0;
		try
		{
			while((line = reader.readLine()) != null)
			{
				StringTokenizer st = new StringTokenizer(line, "- :\t");
				while(st.hasMoreTokens())
				{
					try
					{
						int year = Integer.parseInt(st.nextToken());
						int month = Integer.parseInt(st.nextToken());
						int day = Integer.parseInt(st.nextToken());
						int hour = Integer.parseInt(st.nextToken());
						int minute = Integer.parseInt(st.nextToken());
						int second = Integer.parseInt(st.nextToken());
						String name = st.nextToken();
						Player player = World.getPlayer(name);
						if(player != null && player.isOnline())
						{
							Calendar calendar = Calendar.getInstance();
							calendar.set(Calendar.YEAR, year);
							calendar.set(Calendar.MONTH, month);
							calendar.set(Calendar.DAY_OF_MONTH, day);
							calendar.set(Calendar.HOUR_OF_DAY, hour);
							calendar.set(Calendar.MINUTE, minute);
							calendar.set(Calendar.SECOND, second);
							calendar.set(Calendar.MILLISECOND, 0);
							long time = calendar.getTimeInMillis() / 1000;
							checkAndSave(name, time);
						}
						i++;
					}
					catch(Exception e)
					{
					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	private void checkAndSave(String name, long time)
	{
		Connection tc = null;
		PreparedStatement fps = null;
		ResultSet rs = null;
		try
		{
			tc = DatabaseFactory.getInstance().getConnection();
			fps = tc.prepareStatement("SELECT * FROM `character_l2top_votes` WHERE `name`=? AND `time`=? LIMIT 1");
			fps.setString(1, name);
			fps.setLong(2, time);
			rs = fps.executeQuery();
			if(!rs.next())
			{
				Player player = World.getPlayer(name);
				if(player != null && player.isOnline())
				{
					player.getInventory().addItem(Config.L2_TOP_REWARD_ITEM_ID, Config.L2_TOP_REWARD_ITEM_COUNT);
					player.sendMessage("Вам начислено " + Config.L2_TOP_REWARD_ITEM_COUNT + " " + getItemName(Config.L2_TOP_REWARD_ITEM_ID) + " за голосование в рейтинге L2Top.");
					_log.info("player credited " + Config.L2_TOP_REWARD_ITEM_COUNT + " " + getItemName(Config.L2_TOP_REWARD_ITEM_ID) + " for voting in the ranking L2Top.");
					fps = tc.prepareStatement("INSERT INTO `character_l2top_votes` (`name`, `time`) VALUES (?, ?)");
					fps.setString(1, name);
					fps.setLong(2, time);
					fps.execute();
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			DbUtils.closeQuietly(tc, fps, rs);
		}
	}
	
	public static String getItemName(int ItemId)
	{
		return ItemHolder.getInstance().getTemplate(ItemId).getName();
	}
}